//
//  YZMpayZFFormViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/7/11.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMpayFormViewController.h"
#import "YZMHintInputView.h"
#import "NSNumber+Utils.h"
#import "UIViewController+Utils.h"
#import "YZMAppHelper.h"
#import "YZClient.h"
#import "MBProgressHUD+Utils.h"
#import <BlocksKit/UIControl+BlocksKit.h>
#import "YZMAppHelper.h"
#import "YZMAlertView.h"

#define sYZMRechargepayAccountDefault  @"YZMRechargepayAccountDefault"

@interface YZMpayFormViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UILabel *balanceLB;
@property (nonatomic, strong) YZMHintInputView *accountInput;
@property (nonatomic, strong) YZMHintInputView *amountInput;
@property (nonatomic, strong) UIButton  *nextButton;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *timeDescLabel;
@property (nonatomic, strong) UILabel *callLabel;
@property (nonatomic, strong) UIButton *helpBT;
@property (nonatomic, assign) double money;


@end

@implementation YZMpayFormViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.title = @"支付宝转账";
    [self createObjects];
    [self checkIfButtonEnable];
    [self registerForKeyboardAutoWithBottomView:_bottomView];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    if (!YZMUserServiceInstance.user.detail.isNamed) {
        
        YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"您还未实名认证，请先认证"];
        alertView.cancelButton.hidden = NO;
        [alertView.sureButton setTitle:@"立即验证" forState:UIControlStateNormal];
        alertView.cancleHandle = ^{
            
            [YZMHCMInstance popViewController:nil animated:YES];
        };
        alertView.confirmHandle  = ^{
            
            [YZMHCMInstance pushViewControllerWithName:@"identifyVerify" andParams:nil];
            return YES;
        };
        [alertView showInView:self.navigationController.view];
        
        return;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark -- network

- (void)payZFRequestSubmit
{
    
#if defined(DEBUG_MODE) || defined(TEST_MODE)
    
    if ([@(0.01) isGreaterThanDouble: [self.amountInput.textField.text doubleValue]]) {
        
        [MBProgressHUD showMessage:@"最低0.01元起充"];
        return;
    }
#else
    if ([@(1.0) isGreaterThanDouble: [self.amountInput.textField.text doubleValue]]) {
        
        [MBProgressHUD showMessage:@"最低1元起充"];
        return;
    }
#endif
    if ([@(1.0) isGreaterThanDouble: [self.amountInput.textField.text doubleValue]]) {
        
        [MBProgressHUD showMessage:@"最低1元起充"];
        return;
    }
    
    if ([@([self.amountInput.textField.text doubleValue]) isGreaterThanDouble: 100000.0]) {
        
        [MBProgressHUD showMessage:@"单次充值最高10万元"];
        return;
    }
    
//    /*保存账号*/
//    if (YZMUserServiceInstance.currentUser) {
//        
//        [[NSUserDefaults standardUserDefaults] setObject:self.accountInput.textField.text forKey:[NSString stringWithFormat:@"%@_%@", sYZMRechargepayZFAccountDefault, YZMUserServiceInstance.currentUser.userID]];
//    }
    
    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"请求中"];
    
    [YZClient rd_payRequestWithMoney:[self.amountInput.textField.text trimSpace] andAccount:self.accountInput.textField.text success:^(NSURLResponse *task, id responseObject) {
        
        [hud hide:NO];
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [self showNextPage];
        }
        else
        {
            [topModel showMessage];
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}


#pragma mark -- click event

- (void)showNextPage{
    
    [self resignFirstResponderAll];
    if (!([self.accountInput.textField.text yz_isValidPhoneString] || [self.accountInput.textField.text yz_isValidEmail])) {
        
        [MBProgressHUD showMessage:@"支付宝账号输入错误"];
        return;
    }
    
    NSString *str = @"alip";
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@",str,@"ays://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=https%3A%2F%2Fqr.alip",@"ay.com%2FFKX06144M5DZVYZIGM6SCA%3F_s%3Dweb-other"]];
    [[UIApplication sharedApplication] openURL:url];
}

#pragma mark -- check

- (BOOL)checkIfButtonEnable{
    
    if (self.accountInput.textField.text.length > 0 && self.amountInput.textField.text.length > 0) {
        self.nextButton.layer.borderWidth=0.0;
        self.nextButton.enabled = YES;
        return YES;
    }
    self.nextButton.layer.borderWidth=1.0;
    self.nextButton.enabled = NO;
    return NO;
}


#pragma mark -- textfield 

- (void)textValueChanged: (UITextField *)field
{
    if ([field isEqual:self.amountInput.textField]) {
        
        if ([field.text isEqualToString:@"."]) {
            
            /*第一位为.时，变更为0.*/
            field.text = @"0.";
        }
    }
    
    [self checkIfButtonEnable];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([textField isEqual:self.amountInput.textField]) {
        
        if (!string || string.length == 0) {
            
            return YES;
        }
        
        if ([string isEqualToString:@"."]) {
            
            NSRange range = [textField.text rangeOfString:@"."];
            if (range.length != 0) {
                return FALSE;
            }
            
        }else{
            
            NSRange range = [textField.text rangeOfString:@"."];
            if( range.length != 0 && textField.text.length - range.location >2){
                
                return false;
            }
        }
    }
    
    return YES;
}


#pragma mark -- ui

- (void)createObjects
{
    _bottomView = [UIView new];
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.bottom.equalTo(self.view);
        maker.height.mas_equalTo(0);
    }];
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview: self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.right.equalTo(self.view);
        make.bottom.equalTo(_bottomView.mas_top);
    }];
    
    UIView *balanceView = [UIView new];
    balanceView.backgroundColor = [YZMAppStyle colorForMain];
    [self.scrollView addSubview:balanceView];
    [balanceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    UIView *lineView = [YZMAppStyle splitLine];
    [balanceView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(balanceView);
    }];
    
    self.balanceLB = [YZMAppStyle labelWithLargeWhite];
    self.balanceLB.text = [@"账户余额：" stringByAppendingFormat:@"%@元", @(YZMUserServiceInstance.user.assets.balance).decimalP02fString];
    [balanceView addSubview:self.balanceLB];
    [self.balanceLB mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.top.equalTo(balanceView).offset(20);
        maker.left.equalTo(balanceView).offset(15);
        maker.bottom.equalTo(balanceView).offset(-20);
    }];

    self.accountInput = [YZMHintInputView new];
    [self.scrollView addSubview: self.accountInput];
    self.accountInput.inputLabel.text = @"支付宝账号";
    self.accountInput.textField.placeholder = @"请输入支付宝账号";
    self.accountInput.lineTopView.hidden = YES;
    self.accountInput.lineBottomView.hidden = YES;
    
    [self.accountInput.textField addTarget: self action: @selector(textValueChanged:) forControlEvents: UIControlEventEditingChanged];
    [self.accountInput mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.height.mas_equalTo(44);
        make.top.equalTo(balanceView.mas_bottom).offset(20);
    }];
    
    //显示认证账号
    if (YZMUserServiceInstance.user.detail.payZFAccount.length>0) {
        
        self.accountInput.textField.text = YZMUserServiceInstance.user.detail.payZFAccount;
        self.accountInput.textField.enabled = NO;
        UIImageView *imageViewArrow = [UIImageView new];
        [self.accountInput addSubview:imageViewArrow];
        [imageViewArrow setImage:[UIImage imageNamed:@"left_arrow"]];
        [imageViewArrow mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.right.equalTo(self.accountInput).offset(-16);
            make.centerY.equalTo(self.accountInput.textField);
        }];
        
        UIButton *changepayZFAccountBtn = [UIButton new];
        [self.accountInput addSubview:changepayZFAccountBtn];
        [changepayZFAccountBtn setTitle:@"修改" forState:UIControlStateNormal];
        [changepayZFAccountBtn setTitleColor:[YZMAppStyle colorForLightBlueText] forState:UIControlStateNormal];
        changepayZFAccountBtn.titleLabel.font = [YZMAppStyle mediumSizeFont];
        [changepayZFAccountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.right.equalTo(imageViewArrow.mas_left).offset(-15);
            make.centerY.equalTo(imageViewArrow);
        }];
        [changepayZFAccountBtn bk_addEventHandler:^(id sender) {
            
            [YZMAppHelper changepayZFAccount];
        } forControlEvents:UIControlEventTouchUpInside];
    }else{
        
        self.accountInput.textField.enabled = YES;
    }
    
    self.amountInput = [[YZMHintInputView alloc] init];
    [self.scrollView addSubview: self.amountInput];
    self.amountInput.textField.delegate = self;
    self.amountInput.inputLabel.text = @"充值金额";
    self.amountInput.textField.keyboardType = UIKeyboardTypeDecimalPad;
    self.amountInput.textField.placeholder = @"请输入金额";
    [self.amountInput updateLineIndentationMethod:self.amountInput.lineTopView enumeration:LINE_INDENT_SCENE_LEFT indentValue:15];
    self.amountInput.textField.text = ([@(_money) isGreaterThanDouble:0.0]? @(_money).p02fString:nil);
    
    self.amountInput.lineBottomView.hidden=NO;
    
    [self.amountInput.textField addTarget: self action: @selector(textValueChanged:) forControlEvents: UIControlEventEditingChanged];
    [self.amountInput mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.height.mas_equalTo(44);
        make.top.equalTo(self.accountInput.mas_bottom);
    }];
    
    UIButton *payZFAccountBtn = [self payZFAccountBtn];
    [self.scrollView addSubview:payZFAccountBtn];
    [payZFAccountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(20);
        make.top.equalTo(self.amountInput.mas_bottom).offset(14);
        if (iPhone6P || iPhone6) make.height.mas_equalTo(29);
        else make.height.mas_equalTo(43);
        make.right.equalTo(self.view).offset(-20);
    }];
    
    self.nextButton = [YZMAppStyle NewsubmitButton];
    [self.scrollView addSubview: self.nextButton];
    [self.nextButton setTitle: @"下一步" forState: UIControlStateNormal];
    self.nextButton.enabled = NO;
    [self.nextButton bk_addEventHandler:^(id sender) {
        
        [self payZFRequestSubmit];
        
    } forControlEvents:UIControlEventTouchUpInside];
    self.nextButton.enabled = NO;
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).with.offset(PAGECONTENTMARGIN);
        make.trailing.equalTo(self.view).with.offset(-PAGECONTENTMARGIN);
        make.height.mas_equalTo(44);
        make.top.equalTo(payZFAccountBtn.mas_bottom).with.offset(30);
    }];

    self.timeLabel  = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:[YZMAppStyle colorForLightGrayText]];
    [self.scrollView addSubview: self.timeLabel];
    self.timeLabel.text = @"到帐时间";
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.nextButton.mas_bottom).with.offset(30);
    }];

    self.timeDescLabel = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:[YZMAppStyle colorForLightGrayText]];
    [self.scrollView addSubview: self.timeDescLabel];
    self.timeDescLabel.text = @"08:30-17:30    （1小时内到账）\n17:30以后（次日09:30前到账）";
    self.timeDescLabel.numberOfLines = 2;
    [self.timeDescLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.timeLabel.mas_bottom).with.offset(10);
    }];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self.timeDescLabel.text  attributes:@{NSParagraphStyleAttributeName: style}];
    self.timeDescLabel.attributedText = attrStr;
    
    self.callLabel = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:[YZMAppStyle colorForLightGrayText]];
    self.callLabel.text = @"如急需到账，请电话";
    [self.scrollView addSubview:self.callLabel];
    [self.callLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.timeDescLabel);
        make.top.equalTo(self.timeDescLabel.mas_bottom).offset(5);
    }];
    
    self.helpBT = [UIButton new];
    self.helpBT.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.helpBT setTitle:@"联系客服。" forState:UIControlStateNormal];
    [self.helpBT setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
    [self.helpBT.titleLabel setFont:[YZMAppStyle smallSizeFont]];
    [self.scrollView addSubview:self.helpBT];
    [self.helpBT bk_addEventHandler:^(id sender) {
        
        [YZMAppHelper callServicePhone];
        
    } forControlEvents:UIControlEventTouchUpInside];
    [self.helpBT mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.equalTo(self.callLabel.mas_trailing);
        make.centerY.equalTo(self.callLabel);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(70);
        make.bottom.equalTo(self.scrollView).offset(-10);
    }];
    
    
    [self.amountInput.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.accountInput.textField);
    }];
}

- (UIButton *)payZFAccountBtn{
    
    UIButton *button = [UIButton new];
    NSString *foreString = @"注：为保证资金安全，请准确填写支付宝账号。若未能正常打开支付宝，请复制账号";
    NSString *AccountString = @"mudao888@yztz.cn";
    NSString *lastString = @",手动去支付宝完成转账。";
    
    button.titleLabel.font = [YZMAppStyle smallSizeFont];
    button.titleLabel.numberOfLines = 0;
    button.titleLabel.textColor = [YZMAppStyle colorForGrayText];
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:[[foreString stringByAppendingString:AccountString] stringByAppendingString:lastString]];
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 3;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
    [attStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForLightBlueText] range:NSMakeRange(foreString.length, AccountString.length)];
    [button setAttributedTitle:attStr forState:UIControlStateNormal];
    
    [button bk_addEventHandler:^(id sender) {
        
        [self copypayZFAccount:AccountString];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

#pragma mark --event
-(void)copypayZFAccount:(NSString *)payZFAccount{
    
    if (payZFAccount) {
        
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = payZFAccount;
        [MBProgressHUD showMessage:@"已成功将账号复制到粘贴板！"];
    }else{
        
        [MBProgressHUD showMessage:@"复制失败，请重试！"];
    }
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMpayFormViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (void)updateWithParams:(NSDictionary *)params{
    
    _money = [params[@"money"] doubleValue];
}

@end
